<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */

/**
 * Home page
 */
class homeController extends appRain_Base_Core
{
    // Controller Name
    public $name = "Home";
    public $dispatch =  Array('preDispatchExclude'=>array(),'postDispatchExclude'=>array());

    /**
     * Function Call before Page action method each time
     */
    public function __preDispatch()
    {
    }

    /**
     * Function Call before Page action method each time
     */
    public function __postDispatch()
    {
    }

    public function do301Action($uriSPart=NULL)
    {
        $this->layout = 'empty';
        Header( "HTTP/1.1 301 Moved Permanently" );
        Header( "Location:" . $this->baseurl("/{$uriSPart}"));
        exit;
    }

	public function fair2011Action($id="")
	{
		$this->addons = array('ajaxsubmit','validation.ext','addthis');
		$this->set("section_title","Free webiste campagin");
		$this->page_title = "Free webiste campagin";
		if(!empty($this->data))
		{
			$capacha = App::Module('Session')->Read('capacha');
			$data = App::InformationSet('clientrequest')->findByEmail($this->data['clientrequest']['email']);

			if($capacha['ccapacha'] != $this->data['clientrequest']['capacha'])
			{
				echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$this->__("Type capacha text cottectly")));
			}
			else if(!isset($this->data['clientrequest']['features']))
			{
				echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$this->__("Select features you want to add.")));
			}
			elseif(!isset($this->data['clientrequest']['tnc']))
			{
				echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$this->__("Please agree with terms and consition.")));
			}
			elseif( !empty($data))
			{
				echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$this->__("Email you entered already exists")));
			}
			else
			{
				$this->data['clientrequest']['comments'] = isset($this->data['clientrequest']['comments'])?
															$this->data['clientrequest']['comments'] :
															"";
			$obj = App::InformationSet('clientrequest')
					->setFullname($this->data['clientrequest']['name'])
					->setEmail($this->data['clientrequest']['email'])
					->setProfession($this->data['clientrequest']['profession'])
					->setFeatures(implode(',',$this->data['clientrequest']['features']))
					->setFemail1($this->data['clientrequest']['femail1'])
					->setFemail2($this->data['clientrequest']['femail2'])
					->setWebsitetitle($this->data['clientrequest']['websitetitle'])
					->setTnc($this->data['clientrequest']['tnc'])
					->setComments($this->data['clientrequest']['comments'])
					->setStatus('Pending')
					->Save();

					$params = Array(
										'ID'=>$obj->getID(),
										'Name'=>$this->data['clientrequest']['name'],
										'Email'=>$this->data['clientrequest']['email'],
										'IP'=>App::Helper('Config')->getServerInfo('REMOTE_ADDR'),
										'Date'=>App::Helper('Date')->dateFormated(NULL,'long')
									);

					App::Helper('EmailTemplate')->setParameters($params)
												->prepare('Freewebsite',true);

					echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Redirect","_location"=>$this->baseUrl("/fair2011/" . $obj->getID())));
			}
			exit;
		}


		$cats = App::CategorySet('faircomponent')->findAll();
		$this->set('cats',$cats);

		if(isset($id))
		{
		 $wcsuccessmessage = $this->pageNameToMetaInfo('wcsuccessmessage');
		 $this->set('wcsuccessmessage',$wcsuccessmessage);
		}

		$this->set("selected","");
		$this->set("id",$id);

	}


    /**
     * Function that render home page
     * This page is set from boot_routher from uri_manager.php
     *
     * @return null
     */
    public function indexAction( $id = NULl )
    {
        $this->addons = array('appslide','glitter','addthis');
        $this->pageNameToMetaInfo('HomePage');

        if(isset($id))
        {
            $this->layout="blank";
            $data  = $this->InformationSet()->findById($id);
            echo $data['description'];
            exit;
        }

        $home_press = App::InformationSet('home-press')->findAll("1 ORDER BY Information.generic ASC",Array(Array("status"=>"Active")));
		$this->set("pressdata",$home_press);

		$home_synopsis = App::InformationSet('home-synopsis')->findAll("1 ORDER BY Information.generic ASC",Array(Array("status"=>"Active")));
		$this->set("home_synopsis",$home_synopsis);

		$doc_info = App::InformationSet('docs-post')->findByPromotehomepage('Yes');
		$this->set("doc_info",$doc_info);

		$notice_info = App::InformationSet('notice')->findAll("1 ORDER BY Information.id DESC",Array(Array("status"=>"Active")));
		$this->set("notice_info",$notice_info);

        $this->set("selected","home");
    }

    public function downloadAction($hash = NULL)
    {
        $pageInfo = $this->pageNameToMetaInfo('Download');
        $this->set('pageInfo',$pageInfo);

		if(isset($hash))
		{
			$this->layout = "empty";
			$hashdecoded = base64_decode($hash);
			$id = substr($hashdecoded,strrpos($hashdecoded,'A') + 1,strlen($hashdecoded));

			$downloadData = App::InformationSet()->findById($id);

			$this->InformationSet('download')->setId($downloadData['id'])->setDownloaded(($downloadData['downloaded']+1))->Save();

			$params = Array(
								'Version'=> "{$downloadData['title']} {$downloadData['version']}",
								'IP'=>App::Helper('Config')->getServerInfo('REMOTE_ADDR'),
								'Date'=>App::Helper('Date')->dateFormated(NULL,'long')
							);

			App::Helper('EmailTemplate')->setParameters($params)
										->prepare('Download',true);

			if($downloadData['version-type']=='QuickStart')
			{
				App::Helper('Config')->transfer('http://code.google.com/p/apprain-quickstart/downloads',"Thank's for your patience! You are being moved to the repository");
			}
			else
			{
				App::Helper('Config')->transfer('http://code.google.com/p/apprain-core/downloads',"Thank's for your patience! You are being moved to the repository");
			}

			exit;
            #$path = $this->basedir("/uploads/filemanager/{$downloadData['source-code']}");
			#header('Content-type: application/zip');
			#header('Content-Disposition: attachment; filename="' . $downloadData['source-code'] . '"');
			#readfile("{$path}");
            #readfile("{$path}");

		}

		$developerEdition = App::InformationSet('download')->findAll("1 ORDER BY GENERIC DESC",Array(Array("version-type"=>"Developer"),"AND",Array("status"=>"Public")));
		$this->set("developerEdition",$developerEdition);
		$quickStartEdition = App::InformationSet('download')->findAll("1 ORDER BY GENERIC DESC",Array(Array("version-type"=>"QuickStart"),"AND",Array("status"=>"Public")));
		$this->set("quickStartEdition",$quickStartEdition);


        $this->set("section_title","Download");
        $this->set("selected","download");
    }

	public function ticketAction($id = NULL)
	{
		//$this->checkAppUserLogin();
		$pageInfo = $this->pageNameToMetaInfo('Ticket');

		if(!empty($this->data))
		{
			try
			{
				if($this->data['Ticket']['name']=='') throw new AppException($this->__('Please enter your name'));
				if( !App::Helper("Validation")->Email($this->data['Ticket']['email'])) throw new AppException($this->__('Please enter a valid email address'));
				if($this->data['Ticket']['title']=='') throw new AppException($this->__('Please enter a subject'));
				if($this->data['Ticket']['description']=='') throw new AppException($this->__('Please enter a description'));

				$capacha = App::Module('Session')->read('capacha');
				if($capacha['ticket']  != $this->data['Ticket']['capacha']) throw new AppException($this->__('Please fillup the capacha text correctly'));

				$userid = $this->appUserLoggedInId();

				if($this->data['Ticket']['file']['name'] != "")
				{
					$filemanager_base_dir = App::load("Helper/Config")->get('filemanager_base_dir') . "/ticket/";
					$imgData = App::Helper("Utility")->upload($this->data['Ticket']['file'],$filemanager_base_dir);
					$this->data['Ticket']['file'] = $imgData['file_name'];
				}
				else $this->data['Ticket']['file'] ='';

				$this->data['Ticket']['userid'] = $userid;
				$this->data['Ticket']['dated'] = date('Y-m-d H:i:s');
				$obj = $this->Ticket->Save($this->data);

				$params = Array(
										'ID'=>$obj->getID(),
										'Name'=>$this->data['Ticket']['name'],
										'Email'=>$this->data['Ticket']['email'],
										'Message'=>$this->data['Ticket']['description'],
										'IP'=>App::Helper('Config')->getServerInfo('REMOTE_ADDR'),
										'Date'=>App::Helper('Date')->dateFormated(NULL,'long')
									);

					App::Helper('EmailTemplate')->setParameters($params)
												->prepare('ContactUs',true);

				$this->redirect("/ticket/" . $obj->getID());
			}
			catch(AppException $e)
			{
				$this->set('error',$e->getMessage());
			}
		}

		$this->set("pageInfo",$pageInfo);
		$this->addons = Array('validation.ext');
		$this->set("section_title","Ticket");
		$this->set("selected","ticket");
		$this->set("id",$id);

	}

	public function searchAction($srcstr = null, $page = 1)
	{
		$this->addons = Array('defaultvalues');

		$srcstr = isset($this->post['ss']) ? $this->post['ss'] : $srcstr;
		$srcData = App::Helper("Search")
					  ->setSmartPaging(true)
					  ->setPage($page)
					  ->setLimit(10)
					  ->setHLink($this->baseurl("/search/{$srcstr}"))
					  ->Search($srcstr);

		$this->set('srcstr', $srcstr);
		$this->set('srcarr', $srcData);

		$this->set("section_title","Search Reasult");
		$this->set("selected","search");
	}
}
